package com.qd.panda.service.park;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.carpark.CarParkDoorpostLoginDTO;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.mapper.park.CarParkDoorpostLoginMapper;
import com.qd.panda.model.CarParkDoorpost;
import com.qd.panda.model.CarParkDoorpostLogin;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 门岗登录信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class CarParkDoorpostLoginService extends BaseService<CarParkDoorpostLoginMapper, CarParkDoorpostLogin> {

    private static final String PREFIX_ID = "panda_car_park_doorpost_login_lid_{0}";
    private static final String PREFIX_LIST = "panda_car_park_doorpost_login_userId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_CAR = "panda_car_park_doorpost_login_did_{0}_parkId_{1}_operator_{2}";

    private static final String OPERATOR = "operator";
    private static final String LOGIN_DOORMAN_STATUS = "login_doorman_status";

    private final RedisTemplateUtil<CarParkDoorpostLogin> redisTemplateUtil;
    private final CarParkDoorpostService carParkDoorpostService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkDoorpostLoginDTO save(CarParkDoorpostLoginDTO dto) {
        checkUnique(dto);
        final CarParkDoorpostLogin model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkDoorpostLoginDTO update(CarParkDoorpostLoginDTO dto) {
        checkUnique(dto);
        final CarParkDoorpostLogin historyModel = Optional.ofNullable(getById(dto.getLid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final CarParkDoorpostLogin model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            clearCache(model);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<CarParkDoorpostLogin> mList) throws ApiException {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<CarParkDoorpostLogin> mList) {
        final List<String> ids = mList.stream().map(CarParkDoorpostLogin::getLid).collect(toList());
        final List<CarParkDoorpostLogin> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param lid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String lid) {
        final CarParkDoorpostLogin model = Optional.ofNullable(getById(lid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(lid)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<CarParkDoorpostLogin> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(CarParkDoorpostLoginDTO dto) {
        final QueryWrapper<CarParkDoorpostLogin> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param lid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String lid) {
        boolean exists = false;
        if (StringUtils.hasLength(lid)) {
            final CarParkDoorpostLogin model = getById(lid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param lid 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkDoorpostLogin getById(String lid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, lid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(lid), CarParkDoorpostLogin.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param lid 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkDoorpostLoginDTO getByIdDto(String lid) {
        return Optional.ofNullable(getById(lid)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkDoorpostLogin getOne(CarParkDoorpostLoginDTO dto) {
        final QueryWrapper<CarParkDoorpostLogin> queryWrapper = createQueryWrapper(dto);
        CarParkDoorpostLogin model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkDoorpostLoginDTO getOneDto(CarParkDoorpostLoginDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<CarParkDoorpostLogin> getList(CarParkDoorpostLoginDTO dto) {
        final QueryWrapper<CarParkDoorpostLogin> queryWrapper = createQueryWrapper(dto);
        final List<CarParkDoorpostLogin> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<CarParkDoorpostLoginDTO> getListDto(CarParkDoorpostLoginDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param did
     * param parkId
     * param operator
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public CarParkDoorpostLogin getUniqueByDidAndParkIdAndOperator(String did, String parkId, String operator) {
        final QueryWrapper<CarParkDoorpostLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("did", did);
        queryWrapper.eq("park_id", parkId);
        queryWrapper.eq(OPERATOR, operator);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, did, parkId, operator);
        final CarParkDoorpostLogin model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), CarParkDoorpostLogin.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(CarParkDoorpostLoginDTO dto) {
        CarParkDoorpostLogin model = getUniqueByDidAndParkIdAndOperator(dto.getDid(), dto.getParkId(), dto.getOperator());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(CarParkDoorpostLoginDTO dto, CarParkDoorpostLogin model) {
        if (!StringUtils.hasLength(dto.getLid())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getLid().equals(model.getLid())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(CarParkDoorpostLogin model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLid()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, model.getDid(), model.getParkId(), model.getOperator()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getOperator()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<CarParkDoorpostLogin> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLid())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> uniquePandaCarList = list.stream().
                filter(carParkDoorpostLogin -> StringUtils.hasLength(carParkDoorpostLogin.getDid()) && StringUtils.hasLength(carParkDoorpostLogin.getParkId()) && StringUtils.hasLength(carParkDoorpostLogin.getOperator()))
                .map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, model.getDid(), model.getParkId(), model.getOperator())).collect(toList());
        if (!uniquePandaCarList.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniquePandaCarList);
            uniquePandaCarList.clear();
        }
        List<String> operatorList = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getOperator())).collect(toList());
        if (!operatorList.isEmpty()) {
            redisTemplateUtil.deleteByKey(operatorList);
            operatorList.clear();
        }
    }


    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public CarParkDoorpostLoginDTO modelToDto(CarParkDoorpostLogin model) {
        if (null == model) {
            return null;
        }
        final CarParkDoorpostLoginDTO dto = new CarParkDoorpostLoginDTO();
        dto.setLid(model.getLid());
        dto.setOperatorTime(model.getOperatorTime());
        dto.setDid(model.getDid());
        dto.setOperator(model.getOperator());
        dto.setOrgId(model.getOrgId());
        dto.setParkId(model.getParkId());
        dto.setLoginDoormanStatus(model.getLoginDoormanStatus());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public CarParkDoorpostLogin dtoToModel(CarParkDoorpostLoginDTO dto) {
        if (null == dto) {
            return null;
        }
        final CarParkDoorpostLogin model = new CarParkDoorpostLogin();
        model.setLid(dto.getLid());
        model.setOperatorTime(dto.getOperatorTime());
        model.setDid(dto.getDid());
        model.setOperator(dto.getOperator());
        model.setOrgId(dto.getOrgId());
        model.setParkId(dto.getParkId());
        model.setLoginDoormanStatus(dto.getLoginDoormanStatus());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(CarParkDoorpostLoginDTO dto) {
        dto.setLoginDoormanStatusDisplay(MbUtil.idToDisplay(dto.getLoginDoormanStatus()));
        dto.setDidDisplay(carParkDoorpostService.idToDisplay(dto.getDid()));
        Optional.ofNullable(carParkDoorpostService.getByIdDto(dto.getDid())).ifPresent(dto::setCarParkDoorpost);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<CarParkDoorpostLoginDTO> modelToDtoList(List<CarParkDoorpostLogin> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<CarParkDoorpostLogin> dtoToModelList(List<CarParkDoorpostLoginDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<CarParkDoorpostLogin> createQueryWrapper(CarParkDoorpostLoginDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<CarParkDoorpostLogin> createQueryWrapper(CarParkDoorpostLoginDTO dto, String tableAlias) {
        final QueryWrapper<CarParkDoorpostLogin> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getDid())) {
                queryWrapper.eq(tableAlias + "did", dto.getDid());
            }
            if (StringUtils.hasLength(dto.getOperator())) {
                queryWrapper.eq(tableAlias + OPERATOR, dto.getOperator());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getParkId())) {
                queryWrapper.eq(tableAlias + "park_id", dto.getParkId());
            }
            if (StringUtils.hasLength(dto.getLoginDoormanStatus())) {
                queryWrapper.eq(tableAlias + LOGIN_DOORMAN_STATUS, dto.getLoginDoormanStatus());
            }
        }
        queryWrapper.orderByAsc(tableAlias + LOGIN_DOORMAN_STATUS);
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<CarParkDoorpostLogin> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<CarParkDoorpostLogin> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(CarParkDoorpostLogin::getLid).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 保安登录门岗，如果没有就创建，有就更新状态和时间
     *
     * @param userId 用户ID
     * @param ids    门岗ID集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void login(String userId, List<String> ids) {
        String currentOrgId = SecurityUtils.getLoginUser().getCurrentOrgId();
        carParkDoorpostService.checkIds(ids);
        List<CarParkDoorpost> list = carParkDoorpostService.listByIds(ids);
        for (CarParkDoorpost carParkDoorpost : list) {
            boolean isUpdate = true;
            CarParkDoorpostLogin model = getUniqueByDidAndParkIdAndOperator(carParkDoorpost.getDid(), carParkDoorpost.getParkId(), userId);
            if (null == model) {
                isUpdate = false;
                model = new CarParkDoorpostLogin();
                model.setDid(carParkDoorpost.getDid());
                model.setParkId(carParkDoorpost.getParkId());
                model.setOperator(userId);
                model.setOrgId(currentOrgId);
            }
            model.setLoginDoormanStatus(PandaConstant.L_DOORMAN_STATUS_1);
            model.setOperatorTime(LocalDateTime.now());
            CarParkDoorpostLoginDTO carParkDoorpostLoginDTO = modelToDto(model);
            if (isUpdate) {
                update(carParkDoorpostLoginDTO);
            } else {
                save(carParkDoorpostLoginDTO);
            }
            carParkDoorpostLoginDTO.freeData();
        }
    }

    /**
     * 保安退出登录门岗
     *
     * @param userId 用户ID
     * @param ids    门岗ID集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void logout(String userId, List<String> ids) {
        QueryWrapper<CarParkDoorpostLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OPERATOR, userId);
        queryWrapper.in("did", ids);
        queryWrapper.eq(LOGIN_DOORMAN_STATUS, PandaConstant.L_DOORMAN_STATUS_1);
        List<CarParkDoorpostLogin> list = getBaseMapper().selectList(queryWrapper);
        queryWrapper.clear();
        Optional.ofNullable(list).ifPresent(l -> {
            l.forEach(c -> c.setLoginDoormanStatus(PandaConstant.L_DOORMAN_STATUS_2));
            updateBatchIds(l);
        });
    }

    /**
     * 查询当前用户对应的门岗信息列表
     *
     * @param personId 当前登录保安
     * @return 门岗信息列表
     */
    @Transactional(readOnly = true)
    public List<CarParkDoorpostLogin> getListByUserId(String personId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, personId);
        return redisTemplateUtil.getList(new CacheKey().setKey(key), () -> {
            QueryWrapper<CarParkDoorpostLogin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OPERATOR, personId);
            final List<CarParkDoorpostLogin> list = super.list(queryWrapper);
            queryWrapper.clear();
            return list;
        }, CarParkDoorpostLogin.class);
    }

    @Transactional(readOnly = true)
    public List<CarParkDoorpostLoginDTO> getListByUserIdDTO(String personId) {
        return Optional.ofNullable(getListByUserId(personId)).map(this::modelToDtoList).orElse(Collections.emptyList());
    }


    /**
     * 查询当前用户对应的门岗名字，并拼装成列表，长度不大于200
     *
     * @param personId 当前登录保安
     * @return 门岗名字
     */
    @Transactional(readOnly = true)
    public String getDoorpostMsg(String personId) {
        final List<CarParkDoorpostLoginDTO> list = getListByUserIdDTO(personId);
        if (list.isEmpty()) {
            return "";
        }
        //获取已登录的门岗信息
        final List<CarParkDoorpostLoginDTO> collect = list.stream().filter(carParkDoorpostLoginDTO -> carParkDoorpostLoginDTO.getLoginDoormanStatus().equals(PandaConstant.L_DOORMAN_STATUS_1)).collect(toList());
        if (collect.isEmpty()) {
            return "";
        }
        StringBuilder str = new StringBuilder();
        for (CarParkDoorpostLoginDTO carParkDoorpostLogin : collect) {
            if (str.length() + (carParkDoorpostLogin.getDidDisplay().length() + 1) >= 200) {
                break;
            }
            str.append(carParkDoorpostLogin.getDidDisplay());
            str.append(",");
        }
        if (str.lastIndexOf(",") != -1) {
            return str.substring(0, str.length() - 1);
        }
        return str.toString();
    }
}